package de.unibi.comet.ac;

import de.unibi.comet.qsufsort.QSufSort;
import de.unibi.comet.qsufsort.SWIGTYPE_p_int;

/** Contains a method for suffix array construction. */
public class SuffixArrayFactory {
	
	/** Wraps qsufsort. */
	public static int[] create(String s) {
		int[] sa = new int[s.length()];
		System.loadLibrary("qsufsort");
		SWIGTYPE_p_int c_sa = QSufSort.build_suffix_array(s);
		for (int i = 0; i < sa.length; i++) {
			int n = QSufSort.get(c_sa, i);
			if (n < 0) {
				QSufSort.free_array(c_sa);
				throw new IndexOutOfBoundsException("qsufsort failed");
			}
			sa[i] = n;
		}
		QSufSort.free_array(c_sa);
		return sa;
	}

	/** Wraps qsufsort. */
	public static int[] create(int[] s) {
		int[] sa = new int[s.length];
		System.loadLibrary("qsufsort");
		SWIGTYPE_p_int c_s = QSufSort.alloc_array(s.length);
		for (int i=0; i<s.length; ++i) {
			QSufSort.set(c_s, i, s[i]);
		}
		for (int i=0; i<s.length; ++i) {
			int n = QSufSort.get(c_s, i);
			QSufSort.set(c_s, i, n);
		}
		SWIGTYPE_p_int c_sa = QSufSort.build_suffix_array_int(c_s);
		for (int i = 0; i < sa.length; i++) {
			int n = QSufSort.get(c_sa, i);
			if (n < 0) {
				QSufSort.free_array(c_s);
				QSufSort.free_array(c_sa);
				throw new IndexOutOfBoundsException("qsufsort failed");
			}
			sa[i] = n;
		}
		QSufSort.free_array(c_s);
		QSufSort.free_array(c_sa);
		return sa;
	}
}
